import React from 'react';
import { Button, Icon, Modal } from 'antd';
import {
  WeaTools,
  WeaLocaleProvider,
  WeaTop,
  WeaDialog,
  WeaSearchGroup,
  WeaFormItem,
  WeaInput,
  WeaCheckbox,
  WeaBrowser,
  WeaInputNumber,
  WeaSelect,
  WeaUpload,
  WeaRichText,
  WeaFieldTemplateSelect,
  WeaHelpfulTip,
  WeaAvatar,
} from 'ecCom';
import { WeaForm, WeaSwitch } from 'comsMobx';

const getLabel = WeaLocaleProvider.getLabel;

const basicToolBar = {
  toolbar: [
    { name: 'paragraph', items: ['JustifyLeft', 'JustifyCenter', 'JustifyRight'] },
    { name: 'styles', items: ['Font', 'FontSize'] },
    { name: 'colors', items: ['TextColor'] },
  ],
};

class WeaSystemSetting extends React.Component {
  state = {
    loading: false,
    data: {},
    wmSetting: {},
    textVisible: false,
    textTemp: { wmwidth: '', wmheight: '', wmcontent: '' },
    imgTemp: { wmwidth: '', wmheight: '' },
    labelList: [],
    textEdited: false,
    clientTypeValue: '',
    optionList: [],
    avatarCondition: [],
    avatarForm: {},
    avatarValue: '',
    mBackColor: '',
    mFontColor: '',
    fBackColor: '',
    fFontColor: '',
    ffixedimageid: '',
    mfixedimageid: '',
    mPreview: '',
    fPreview: '',
    headPreview: '',
    canEdit: '',
  };

  constructor(props) {
    super(props);
    this.getButtons = this.getButtons.bind(this);
    this.onChange = this.onChange.bind(this);
    this.onWmChange = this.onWmChange.bind(this);
    this.onSave = this.onSave.bind(this);
    this.onCancel = this.onCancel.bind(this);
    this.onLoad = this.onLoad.bind(this);
    this.setImageSize = this.setImageSize.bind(this);
    this.getPreviewHref = this.getPreviewHref.bind(this);
    this.onSaveTextDailog = this.onSaveTextDailog.bind(this);
    this.setScrolledHeight = this.setScrolledHeight.bind(this);
    this.getPluginSettings = this.getPluginSettings.bind(this);
  }

  componentWillMount() {
    const { display, visible } = this.props;
    if (display == 'page' || visible) {
      this.onLoad();
    }
  }

  componentDidMount() {
    this.getPluginSettings();
  }

  render() {
    const { display, visible } = this.props;
    const {
      loading,
      data,
      textVisible,
      textTemp,
      labelList,
      wmSetting,
      textEdited,
      clientTypeValue,
      optionList,
      avatarForm,
      avatarCondition,
    } = this.state;
    const {
      canEdit = false,
      oaaddress,
      licenseRemind,
      remindUserNames,
      remindDays,
      picturePath,
      filesystem,
      filesystembackup,
      filesystembackuptime,
      needzip,
      isaesencrypt,
      unsystem_help,
    } = data;
    const { isopen, mobileisopen, watermarktype, opacity, rotate, imageid } = wmSetting;
    const { wmcontent } = textTemp;
    const disabled = !canEdit;
    const colProps = { labelCol: { span: 8 }, wrapperCol: { span: 16 } };

    const Content = (
      <React.Fragment ecId={`${this && this.props && this.props.ecId || ''}_React.Fragment@cili4m`}>
        <WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@b9p3o9`} title={getLabel(33174, '全局设置')} showGroup={true} center size="large">
          <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@5lsa3b`} label={getLabel(21870, 'OA访问地址')} {...colProps}>
            <WeaInput ecId={`${this && this.props && this.props.ecId || ''}_WeaInput@pll6qh`} value={oaaddress} disabled={disabled} onChange={value => this.onChange({ oaaddress: value })} />
          </WeaFormItem>
          {canEdit ? (
            <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@eutf6o`} label={getLabel(33386, '授权信息到期提醒')} {...colProps}>
              <WeaCheckbox ecId={`${this && this.props && this.props.ecId || ''}_WeaCheckbox@abm0xd`} display="switch" value={licenseRemind} onChange={value => this.onChange({ licenseRemind: value })} />
            </WeaFormItem>
          ) : (
            ''
          )}
          {canEdit && licenseRemind == '1' ? (
            <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@sgqrbw`} label={getLabel(18013, '提醒对象')} {...colProps}>
              <WeaBrowser ecId={`${this && this.props && this.props.ecId || ''}_WeaBrowser@cp8gz6`}
                type={17}
                title={getLabel(18013, '提醒对象')}
                isSingle={false}
                replaceDatas={remindUserNames}
                onChange={(ids, names, datas) => this.onChange({ remindUsers: ids, remindUserNames: datas })}
              />
            </WeaFormItem>
          ) : (
            ''
          )}
          {canEdit && licenseRemind == '1' ? (
            <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@3e6oan`} label={getLabel(32089, '提前提醒天数')} {...colProps}>
              <WeaInput ecId={`${this && this.props && this.props.ecId || ''}_WeaInput@jsjqow`} value={remindDays} onChange={value => this.onChange({ remindDays: value })} />
            </WeaFormItem>
          ) : (
            ''
          )}
          {canEdit ? (
            <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@uugq2x`} label={getLabel(507063, '禁用系统帮助')} {...colProps}>
              <WeaCheckbox ecId={`${this && this.props && this.props.ecId || ''}_WeaCheckbox@dgh7d0`} display="switch" value={unsystem_help} onChange={value => this.onChange({ unsystem_help: value })} />
            </WeaFormItem>
          ) : (
            ''
          )}
        </WeaSearchGroup>
        <WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@8tctue`} title={getLabel(33389, '文件存储设置')} showGroup={true} center size="large">
          <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@5okhv9`} label={getLabel(20231, '图片存放目录')} {...colProps}>
            <WeaInput ecId={`${this && this.props && this.props.ecId || ''}_WeaInput@r643nx`}
              helpfulTip={canEdit ? getLabel(33390, '设置文件目录路径不能含有中文，不填写将默认存放在系统程序目录filesystem下') : ''}
              value={picturePath}
              disabled={disabled}
              onChange={value => this.onChange({ picturePath: value })}
            />
          </WeaFormItem>
          <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@d90eco`} label={getLabel(15046, '文件存放目录')} {...colProps}>
            <WeaInput ecId={`${this && this.props && this.props.ecId || ''}_WeaInput@g84ysh`}
              helpfulTip={canEdit ? getLabel(33390, '设置文件目录路径不能含有中文，不填写将默认存放在系统程序目录filesystem下') : ''}
              value={filesystem}
              disabled={disabled}
              onChange={value => this.onChange({ filesystem: value })}
            />
          </WeaFormItem>
          <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@jduvl4`} label={getLabel(15047, '文件备份目录')} {...colProps}>
            <WeaInput ecId={`${this && this.props && this.props.ecId || ''}_WeaInput@envpzh`}
              viewAttr="3"
              defaultValue={'/oa/weaver/ecology/filesystembackup'}
              helpfulTip={canEdit ? getLabel(514460, '设置文件目录路径不能含有中文，默认存放在系统程序目录filesystembackup下') : ''}
              value={filesystembackup}
              disabled={disabled}
              onChange={value => this.onChange({ filesystembackup: value })}
            />
          </WeaFormItem>
          <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@oc7o1u`} label={getLabel(15048, '文件备份周期')} {...colProps}>
            <WeaInput ecId={`${this && this.props && this.props.ecId || ''}_WeaInput@22osjk`}
              viewAttr="3"
              defaultValue={1440}
              helpfulTip={canEdit ? getLabel(514459, '单位：分钟，默认备份周期是一天（1440分钟），周期必须大于等于60分钟小于等于1440分钟') : ''}
              value={filesystembackuptime}
              disabled={disabled}
              onChange={value => this.onChange({ filesystembackuptime: value })}
            />
          </WeaFormItem>
          <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@besp3x`} label={getLabel(33391, '压缩存储')} {...colProps}>
            <WeaCheckbox ecId={`${this && this.props && this.props.ecId || ''}_WeaCheckbox@yw2vmj`} display="switch" value={needzip} disabled={disabled} onChange={value => this.onChange({ needzip: value })} />
          </WeaFormItem>
          <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@e5km3k`} label={getLabel(33392, '加密存储')} {...colProps}>
            <WeaCheckbox ecId={`${this && this.props && this.props.ecId || ''}_WeaCheckbox@gg36gv`} display="switch" value={isaesencrypt} disabled={disabled} onChange={value => this.onChange({ isaesencrypt: value })} />
          </WeaFormItem>
        </WeaSearchGroup>
        <WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@7y8rzg`} title={getLabel(504453, '系统默认水印')} showGroup={true} center size="large">
          <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@e620jd`}
            className="weatermark-text-dailog"
            visible={textVisible}
            title={getLabel(504454, '水印内容设置')}
            icon="icon-coms02-currency"
            iconBgcolor="#a7adb5"
            zIndex={200}
            hasScroll={true}
            style={{ width: 600, height: 520 }}
            buttons={[
              <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@mnxms5`} type="primary" onClick={this.onSaveTextDailog}>
                {getLabel(30986, '保存')}
              </Button>,
            ]}
            onCancel={() =>
              this.setState({
                textVisible: false,
                textTemp: {
                  wmwidth: wmSetting.wmwidth,
                  wmheight: wmSetting.wmheight,
                  wmcontent: wmSetting.wmcontent,
                },
              })
            }
          >
            <WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@b3lbxi`} title={getLabel(504455, '水印大小设置')} showGroup={true} center size="large">
              <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@u645c3`} label={`${getLabel(504456, '水印宽度')}(px)`} {...colProps}>
                <WeaInputNumber ecId={`${this && this.props && this.props.ecId || ''}_WeaInputNumber@sqhgoq`}
                  value={textTemp.wmwidth}
                  viewAttr="3"
                  min={100}
                  step={10}
                  onChange={value => this.setState({ textTemp: { ...textTemp, wmwidth: value } })}
                />
              </WeaFormItem>
              <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@rrlpz9`} label={`${getLabel(504457, '水印高度')}(px)`} {...colProps}>
                <WeaInputNumber ecId={`${this && this.props && this.props.ecId || ''}_WeaInputNumber@n0rneg`}
                  value={textTemp.wmheight}
                  viewAttr="3"
                  min={100}
                  step={10}
                  onChange={value => this.setState({ textTemp: { ...textTemp, wmheight: value } })}
                />
              </WeaFormItem>
            </WeaSearchGroup>
            <WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@yaus7f`} title={getLabel(33368, '内容')} showGroup={true} center>
              <div className="watermark-text-content">
                <div className="watermark-text-content-left">
                  <WeaRichText ecId={`${this && this.props && this.props.ecId || ''}_WeaRichText@i6x6nr`}
                    ref={ref => this.setScrolledHeight(ref)}
                    ckConfig={basicToolBar}
                    value={textTemp.wmcontent}
                    onChange={v => this.setState({ textTemp: { ...textTemp, wmcontent: v } })}
                  />
                </div>
                <div className="watermark-text-content-right">
                  <WeaFieldTemplateSelect ecId={`${this && this.props && this.props.ecId || ''}_WeaFieldTemplateSelect@fv9o2j`}
                    scrolledHeight={this.scrolledHeight}
                    options={labelList || []}
                    searchValue={''}
                    onClick={key => this.richText.insertHTML(key)}
                  />
                </div>
              </div>
            </WeaSearchGroup>
          </WeaDialog>
          <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@cog0jc`} label={getLabel(26472, '启用')} {...colProps}>
            <WeaCheckbox ecId={`${this && this.props && this.props.ecId || ''}_WeaCheckbox@6zsd75`} disabled={!canEdit} display="switch" value={isopen} onChange={value => this.onWmChange({ isopen: value })} />
          </WeaFormItem>
          {canEdit &&
            Number(isopen) === 1 && [
              <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@ezbig7`} label={getLabel(504458, '移动端显示水印')} {...colProps}>
                <WeaCheckbox ecId={`${this && this.props && this.props.ecId || ''}_WeaCheckbox@efursu`} display="switch" value={mobileisopen} onChange={value => this.onWmChange({ mobileisopen: value })} />
              </WeaFormItem>,
            ]}
          {canEdit && [
            <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@uu05pd`} label={getLabel(504459, '网页水印类型')} {...{ ...colProps, wrapperCol: { span: 6 } }}>
              <WeaSelect ecId={`${this && this.props && this.props.ecId || ''}_WeaSelect@awqfgg`}
                helpfulTip={canEdit ? getLabel(504460, '水印功能不支持IE10及以下版本的浏览器') : ''}
                options={[
                  { key: '1', selected: true, showname: getLabel(608, '文本') },
                  { key: '2', selected: false, showname: getLabel(74, '图片') },
                ]}
                value={String(watermarktype)}
                detailtype={3}
                supportCancel={false}
                onChange={(v) => {
                  let fix = {};
                  if (v == '1') {
                    fix = {
                      wmwidth: textTemp.wmwidth,
                      wmheight: textTemp.wmheight,
                    };
                  }
                  this.onWmChange({ watermarktype: Number(v), ...fix });
                }}
              />
            </WeaFormItem>,
            <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@9kuhc5`} label={getLabel(504461, '网页水印内容')} {...colProps}>
              {watermarktype === 2 ? (
                <div className="watermark-content">
                  {imageid && imageid != -1 ? (
                    <div className="watermark-content-image">
                      <img onLoad={e => this.setImageSize(e.target)} width={50} src={`/weaver/weaver.file.FileDownload?fileid=${imageid}`} atl="" />
                      <span className="watermark-content-image-del">
                        <Icon ecId={`${this && this.props && this.props.ecId || ''}_Icon@1x3b9y`} type="cross-circle" onClick={() => this.onWmChange({ imageid: '' })} />
                      </span>
                    </div>
                  ) : (
                    <WeaUpload ecId={`${this && this.props && this.props.ecId || ''}_WeaUpload@0sb5q1`}
                      title={getLabel('20001', '上传图片')}
                      btnSize="small"
                      maxFilesNumber={1}
                      uploadUrl="/api/doc/upload/uploadFile"
                      category="string"
                      limitType="jpg,gif,png"
                      clearWhenReset={false}
                      showClearAll={false}
                      onChange={ids => this.onWmChange({ imageid: ids[0] })}
                    />
                  )}
                  {imageid && imageid != -1 ? this.getPreviewHref() : Number(isopen) === 1 ? <span className="required upload" /> : null}
                </div>
              ) : (
                <div className="watermark-content">
                  <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@da8rsa`} className="watermark-content-setting" icon="setting" onClick={() => this.setState({ textVisible: true })} />
                  {textEdited ? <Icon ecId={`${this && this.props && this.props.ecId || ''}_Icon@j17df1`} type="check" className="success" /> : Number(isopen) === 1 ? <span className="required" /> : null}
                  {wmcontent && this.getPreviewHref()}
                </div>
              )}
            </WeaFormItem>,
            <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@wrtw1m`} label={getLabel(504462, '不透明（百分比）')} {...colProps}>
              <WeaInputNumber ecId={`${this && this.props && this.props.ecId || ''}_WeaInputNumber@0tzoyr`} value={opacity} max={100} min={0} onChange={value => this.onWmChange({ opacity: value })} />
            </WeaFormItem>,
            <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@1x1yku`} label={getLabel(504463, '旋转角度（逆时针）')} {...colProps}>
              <WeaInputNumber ecId={`${this && this.props && this.props.ecId || ''}_WeaInputNumber@jbfg92`} value={rotate} max={360} min={0} onChange={value => this.onWmChange({ rotate: value })} />
            </WeaFormItem>,
            <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@75oepq`} label={getLabel(504464, '附件水印设置')} {...colProps}>
              <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@md084b`}
                className="watermark-attachment-setting"
                icon="setting"
                onClick={() => window.open('/wui/engine.html#/docengine/sec/applysetting?watermark=2', '_blank')}
              />
              {canEdit ? <WeaHelpfulTip ecId={`${this && this.props && this.props.ecId || ''}_WeaHelpfulTip@fu9xdu`} style={{ verticalAlign: 'middle' }} title={getLabel(504465, '附件文件中显示的水印与网页水印不同，需单独设置')} /> : ''}
            </WeaFormItem>,
          ]}
        </WeaSearchGroup>
        <WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@gtooe8`}
          title={
            <span>
              <span style={{ marginRight: '10px' }}>{getLabel(507449, '国产操作系统环境下的插件设置')}</span>
              <WeaHelpfulTip ecId={`${this && this.props && this.props.ecId || ''}_WeaHelpfulTip@g7y0hc`} title={getLabel(507455, '非国产操作系统，此设置无效')} placement="top" />
            </span>
          }
          showGroup={true}
          center
          size="large"
        >
          <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@dhowvj`} label={getLabel(501599, '插件类型')} {...colProps}>
            <WeaSelect ecId={`${this && this.props && this.props.ecId || ''}_WeaSelect@jlfm9z`}
              options={optionList}
              value={clientTypeValue}
              viewAttr={canEdit ? 2 : 1}
              onChange={(v) => {
                this.setState({ clientTypeValue: v });
              }}
            />
          </WeaFormItem>
        </WeaSearchGroup>
        {avatarCondition.length > 0 && this.getWriteForm(avatarForm, avatarCondition)}
      </React.Fragment>
    );

    if (display == 'page') {
      return (
        <WeaTop ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@fmi9yn`}
          loading={loading}
          title={getLabel(774, '系统设置')}
          icon={<i className="icon-coms02-currency" />}
          iconBgcolor="#a7adb5"
          buttons={this.getButtons()}
        >
          {Content}
        </WeaTop>
      );
    }

    return (
      <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@2npd44`}
        visible={visible}
        loading={loading}
        title={getLabel(774, '系统设置')}
        icon="icon-coms02-currency"
        iconBgcolor="#a7adb5"
        style={{ width: 700, height: 520 }}
        zIndex={100}
        hasScroll={true}
        buttons={this.getButtons()}
        onCancel={this.onCancel}
      >
        {Content}
      </WeaDialog>
    );
  }

  getButtons() {
    const { data } = this.state;
    const buttons = [];
    if (data.canEdit) {
      buttons.push(
        <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@4lkuj5`} type="primary" onClick={this.onSave}>
          {getLabel(30986, '保存')}
        </Button>,
      );
    }
    return buttons;
  }

  setScrolledHeight(ref) {
    // 计算变量关键字列表高度，使其与富文本等高
    this.richText = ref;
    if (!ref || this.scrolledHeight > 0) return;
    let height = 0;
    if (ref && ref.refs.wrap) {
      const top = 37 + 4;
      height = ref.refs.wrap.clientHeight - top;
    }
    this.scrolledHeight = height;
  }

  setImageSize(img) {
    // 获取图片的原始尺寸
    if (img) {
      let fix = {
        wmwidth: img.naturalWidth > 200 ? img.naturalWidth : 200,
        wmheight: img.naturalHeight > 150 ? img.naturalHeight : 150,
      };
      this.setState({ imgTemp: fix });
      this.onWmChange(fix);
    }
  }

  getPreviewHref() {
    const { wmSetting } = this.state;
    let href = '/cloudstore/resource/pc/watermark/preview.html';
    let params = '?';
    Object.keys(wmSetting || {}).forEach((key) => {
      params += `${key}=${encodeURIComponent(wmSetting[key])}&`;
    });
    href += params;
    return (
      <a style={{ paddingLeft: 15 }} href={href} target="_blank">
        {getLabel(221, '预览')}
      </a>
    );
  }

  onSaveTextDailog() {
    const { textTemp } = this.state;
    const { wmcontent, wmwidth, wmheight } = textTemp;
    let isWMCEmpty = !wmcontent;
    if (!isWMCEmpty) {
      const element = window.CKEDITOR.dom.element.createFromHtml(wmcontent);
      isWMCEmpty = element.getText().replace(/[\s\n]/g, '') === '';
    }
    if (!isWMCEmpty && wmwidth && wmheight) {
      this.onWmChange(textTemp);
      this.setState({ textVisible: false, textEdited: true });
    } else {
      let content = '';
      if (!wmwidth) {
        content = getLabel(520158, '请输入水印宽度');
      } else if (!wmheight) {
        content = getLabel(520159, '请输入水印高度');
      } else if (isWMCEmpty) {
        content = getLabel(504467, '请输入文本水印内容');
      }
      Modal.error({ content });
    }
  }

  onWmChange(obj) {
    const { wmSetting } = this.state;
    this.setState({ wmSetting: { ...wmSetting, ...obj } });
  }

  onChange(obj) {
    const { data } = this.state;
    this.setState({ data: { ...data, ...obj } });
  }

  onSave() {
    const { onSave,callbackFn } = this.props;
    const { data, wmSetting, clientTypeValue } = this.state;
    if (
      (wmSetting.isopen === 1 || wmSetting.isopen === '1') &&
      (!wmSetting.watermarktype ||
        (wmSetting.watermarktype === 1 && !wmSetting.wmcontent) ||
        (wmSetting.watermarktype === 2 && (!(wmSetting.imageid && wmSetting.imageid != -1))))
    ) {
      // 水印必填处理
      Modal.error({
        content: wmSetting.watermarktype === 2 ? getLabel(504466, '请选择水印图片') : getLabel(504467, '请输入文本水印内容'),
      });
      return;
    }
    // 验证备份目录内容
    if (data.filesystembackup == '' || data.filesystembackuptime == '') {
      Modal.error({
        content: getLabel(509065, '请输入必填项'),
      });
      return;
    }

    if (data.filesystembackuptime > 1440 || data.filesystembackuptime < 60 || isNaN(data.filesystembackuptime)) {
      Modal.error({
        content: getLabel(514463, '备份周期只能在60分钟到1440分钟之间'),
      });
      return;
    }
    this.setState({ visible: true, loading: true });
    let done = 0;
    let cb = () => {
      done += 1;
      if (done === 2) {
        // 修改水印
        WeaTools.watermark.getSystemSetting();
        this.onCancel();
        if (onSave && typeof onSave == 'function') onSave();
		if (callbackFn && typeof callbackFn == 'function') callbackFn(data);
      }
    };
    WeaTools.callApi('/api/portal/systemInfo/saveSettingData', 'POST', { ...data })
      .then(() => {
        WeaTools.callApi('/api/systeminfo/othersetting/getHelp', 'GET', {}).then((result) => {
          WeaTools.ls.set('showHelp', { showHelp: result.helpmenu });
        });
      })
      .then(cb);
    WeaTools.callApi('/api/doc/console/wmsystemsetting/savewmsetting', 'POST', { ...wmSetting }).then(cb);
    WeaTools.callApi('/api/odoc/odocPluginSettings/savePluginSettings', 'POST', { clientType: clientTypeValue }).then(cb);
    // 头像设置保存
    const { avatarForm } = this.state;
    const params = avatarForm.getFormParams();
    WeaTools.callApi('/api/hrm/systemAvatarSetting/saveAvatarSetting', 'POST', { ...params });
  }

  onCancel() {
    this.props.onShow(false);
  }

  onLoad() {
    this.setState({ loading: true });
    WeaTools.callApi('/api/portal/systemInfo/getSettingData', 'GET', {}).then((result) => {
      const { data } = result;
      // 备份目录为空值时设置默认值
      data.filesystembackup == '' && (data.filesystembackup = '/oa/weaver/ecology/filesystembackup');
      // 备份周期为空为0及大于24小时的都改为一天
      (data.filesystembackuptime == '' || data.filesystembackuptime == 0 || data.filesystembackuptime > 1440) && (data.filesystembackuptime = 1440);
      this.setState({ loading: false, data });
    });
    // 获取水印设置
    WeaTools.callApi('/api/doc/console/wmsystemsetting/getwmsetting', 'GET', {}).then((result) => {
      const { wmSetting } = result;
      if (wmSetting) {
        const { wmwidth, wmheight, wmcontent } = wmSetting;
        this.setState({ wmSetting, imgTemp: { wmwidth, wmheight }, textTemp: { wmwidth, wmheight, wmcontent }, textEdited: !!wmcontent });
      }
    });
    // 获取文本水印变量
    WeaTools.callApi('/api/doc/console/wmsystemsetting/getwmtextparam', 'GET', {}).then((result) => {
      const { labelList } = result;
      this.setState({ labelList });
    });
    // 头像设置
    WeaTools.callApi('/api/hrm/systemAvatarSetting/getAvatarSettingForm', 'GET', {}).then((resp) => {
      // const { avatarForm, avatarCondition, canEdit } = this.state;
      const form = new WeaForm();
      form.initFormFields(resp.condition);
      const { isFormInit } = form;
      if (isFormInit) {
        this.setState({
          avatarCondition: resp.condition,
          avatarForm: form,
          canEdit: resp.canEdit,
        });
        this.getViewStyle();
      }
    });
  }

  // 渲染表单
  getWriteForm = (form, condition) => {
    // form.initFormFields(condition);
    // condition = toJS(condition);
    const { isFormInit } = form;
    const formParams = form.getFormParams();
    let group = [];
    isFormInit &&
      condition &&
      condition.map((c) => {
        let items = [];
        c.items.map((fields) => {
          items.push({
            com: (
              <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@m1uvos`}
                label={`${fields.label}`} // label 标签的文本
                labelCol={{ span: `${fields.labelcol}` }} // label标签占一行比例
                wrapperCol={{ span: `${fields.fieldcol}` }} // 右侧控件占一行比例
                error={form.getError(fields)} // 错误提示: 处理表单中有必填项,保存的校验
                tipPosition="bottom" // 错误提示的显示位置: top/bottom
              >
                <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@rz6q2n`} fieldConfig={{ ...fields, helpfulTip: '' }} form={form} formParams={formParams} onChange={this.onChangeAvatar} />
              </WeaFormItem>
            ),
            colSpan: 1,
          });
        });
        items.push({
          com: (
            <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@jm27z4`}
              label={getLabel(221, '预览')} // label 标签的文本
              labelCol={{ span: 6 }} // label标签占一行比例
              wrapperCol={{ span: 18 }} // 右侧控件占一行比例
            >
              {this.renderViewImage()}
            </WeaFormItem>
          ),
          colSpan: 1,
        });
        group.push(
          <WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@i5ffdz`}
            showGroup={true}
            needTigger={true}
            items={items} // 条目数组数据
            center={true} // 内容是否居中：一般弹框需要
            title={(
              <span>
                <span style={{ marginRight: '10px' }}>{c.title}</span>
                <WeaHelpfulTip ecId={`${this && this.props && this.props.ecId || ''}_WeaHelpfulTip@v80lw6`} title={c.items[0].helpfulTip} placement="top" />
              </span>
            )}
          />,
        );
      });

    return group;
  };

  // 调用样式设置的dialog
  showDialog = (title, url, style, callback, onCancel) => {
    style = style || { width: 800, height: 600 };
    const dialog = WeaTools.createDialog({ moduleName: 'hrm', title, url, style, callback, onCancel, hasScroll: true });
    dialog.show();
  };

  // 默认头像格式选择
  onChangeAvatar = (data) => {
    this.setState({
      avatarValue: data.headformat.value,
    });
  };

  // 获取预览的样式信息
  getViewStyle = () => {
    WeaTools.callApi('/api/hrm/systemAvatarSetting/getStyleSettingData', 'GET', {}).then((resp) => {
      this.state.avatarForm.updateFields({
        headformat: {
          value: resp.headformat,
        },
      });
      this.setState({
        mBackColor: resp.mheadbackcolor,
        mFontColor: resp.mheadfontcolor,
        fBackColor: resp.fheadbackcolor,
        fFontColor: resp.fheadfontcolor,
        ffixedimageid: resp.ffixedimageid,
        mfixedimageid: resp.mfixedimageid,
        mPreview: resp.mPreview,
        fPreview: resp.fPreview,
        headPreview: resp.headPreview,
        avatarValue: resp.headformat,
      });
    });
  };

  // 渲染头像预览图片
  renderViewImage = () => {
    const { avatarValue, mBackColor, mFontColor, fBackColor, fFontColor, ffixedimageid, mfixedimageid, mPreview, fPreview, headPreview, canEdit } = this.state;
    const url = '/spa/hrm/engine.html#/hrmengine/avatarSetting';
    if (avatarValue == 1) {
      // 首字
      return (
        <span className="view-iamge-wrap">
          <span className="view-image" title={getLabel('513082', '男性人员默认头像')} style={{ color: mFontColor, background: mBackColor }}>
            {mPreview}
          </span>
          <span className="view-image" title={getLabel('513083', '女性人员默认头像')} style={{ color: fFontColor, background: fBackColor }}>
            {fPreview}
          </span>
          {canEdit && (
            <a
              style={{ lineHeight: '45px' }}
              onClick={() => this.showDialog(getLabel('514308', '默认头像样式设置'), url, { width: 800, height: 600 }, this.getViewStyle)}
            >
              {getLabel('128334', '样式设置')}
            </a>
          )}
        </span>
      );
    }
    if (avatarValue == 2) {
      // 默认头像
      return (
        <span className="view-iamge-wrap" key={new Date().getTime()}>
          <span className="view-image left" title={getLabel('513082', '男性人员默认头像')}>
            {mfixedimageid == 0 ? (
              <WeaAvatar ecId={`${this && this.props && this.props.ecId || ''}_WeaAvatar@dfq4px`} url={'/messager/images/icon_m_wev9.png'} type={'0'} />
            ) : (
              <WeaAvatar ecId={`${this && this.props && this.props.ecId || ''}_WeaAvatar@462s3d`} url={`/weaver/weaver.file.FileDownload?fileid=${mfixedimageid}`} />
            )}
          </span>
          <span className="view-image right" title={getLabel('513083', '女性人员默认头像')}>
            {ffixedimageid == 0 ? (
              <WeaAvatar ecId={`${this && this.props && this.props.ecId || ''}_WeaAvatar@t58v3h`} url={'/messager/images/icon_w_wev9.png'} type={'0'} />
            ) : (
              <WeaAvatar ecId={`${this && this.props && this.props.ecId || ''}_WeaAvatar@198g5e`} url={`/weaver/weaver.file.FileDownload?fileid=${ffixedimageid}`} />
            )}
          </span>
          {canEdit && (
            <a
              style={{ lineHeight: '45px' }}
              onClick={() => this.showDialog(getLabel('514308', '默认头像样式设置'), url, { width: 800, height: 600 }, this.getViewStyle)}
            >
              {getLabel('128334', '样式设置')}
            </a>
          )}
        </span>
      );
    }
    if (avatarValue == 3) {
      // 后两字
      return (
        <span className="view-iamge-wrap">
          <span className="view-image" title={getLabel('513082', '男性人员默认头像')} style={{ fontSize: '16px', color: mFontColor, background: mBackColor }}>
            {headPreview}
          </span>
          <span className="view-image" title={getLabel('513083', '女性人员默认头像')} style={{ fontSize: '16px', color: fFontColor, background: fBackColor }}>
            {headPreview}
          </span>
          {canEdit && (
            <a
              style={{ lineHeight: '45px' }}
              onClick={() => this.showDialog(getLabel('514308', '默认头像样式设置'), url, { width: 800, height: 600 }, this.getViewStyle)}
            >
              {getLabel('128334', '样式设置')}
            </a>
          )}
        </span>
      );
    }
  };

  getPluginSettings() {
    // 获取插件列表
    WeaTools.callApi('/api/odoc/odocPluginSettings/getPluginSettings', 'POST', {}).then((result) => {
      const { pluginSetting } = result;
      if (pluginSetting) {
        const { clientTypeValue, optionList } = pluginSetting;
        this.setState({
          clientTypeValue,
          optionList,
        });
      }
    });
  }
}

export default WeaSystemSetting;
